package com.hisense.proxy.busitrans.controller.zndz;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.beust.jcommander.Strings;
import com.hisense.proxy.busitrans.vo.zndz.StatementExcelNameVO;
import com.hisense.proxy.busitrans.vo.zndz.StatementExcelRecordVO;
import com.hisense.proxy.busitrans.vo.zndz.ZndzFtpPwdRelationExcelVO;
import com.hisense.proxy.service.ncc.zndz.FtpExcelFetchService;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *
 * </p>
 *
 * @author tangxqa
 * @since 2021/12/21 2:17 下午
 */
@RestController
@RequestMapping("/ncc/zndz/proxy/ftp/pos")
@Slf4j
public class FtpExcelFetchController {


    @Autowired
    private FtpExcelFetchService ftpExcelFetchService;
    
    @Value("${ncc.zndz.config-file}")
    private String configFilePath;
    
    @Value("${ncc.zndz.pos-file-ddl}")
    private String podFileDdl;



    @GetMapping("/merchantNos")
    public Set<String> getMerchantNos() throws FileNotFoundException {
    	
    	InputStream inputStream = null;
    	if (StringUtils.isEmpty(configFilePath)) {
    		inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("zndz/FTP对照.xlsx");
    	} else {
    		inputStream = new FileInputStream(configFilePath);
    	}
    	
    	List<ZndzFtpPwdRelationExcelVO> excelContent = EasyExcel.read(inputStream)
                .head(ZndzFtpPwdRelationExcelVO.class)
                .headRowNumber(1)
                .sheet().doReadSync();
    	
    	if (excelContent != null && excelContent.size() == 0) {
    		return new HashSet<String>();
    	}
    	
    	Set<String> result = excelContent.stream()
    			.filter(e -> !StringUtils.isEmpty(e.getMerchantNo()))
    			.map(ZndzFtpPwdRelationExcelVO::getMerchantNo)
    			.collect(Collectors.toSet());
    	
    	log.debug("拉取的ftp列表：{}", JSON.toJSON(result));
        return result;
    }
    
    
    
    @SuppressWarnings("deprecation")
	@GetMapping("/excelVos")
    public List<StatementExcelNameVO> getExcelVOs(@RequestParam String merchantNo) throws FileNotFoundException {
    	InputStream inputStream = null;
    	if (StringUtils.isEmpty(configFilePath)) {
    		inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("zndz/FTP对照.xlsx");
    	} else {
    		inputStream = new FileInputStream(configFilePath);
    	}
    	

    	List<ZndzFtpPwdRelationExcelVO> configExcelContent = EasyExcel.read(inputStream)
                .head(ZndzFtpPwdRelationExcelVO.class)
                .headRowNumber(1)
                .sheet().doReadSync();
    	
    	if (configExcelContent != null && configExcelContent.size() == 0) {
    		log.error("未获取到任何商户号的FTP配置!");
    		return new ArrayList<StatementExcelNameVO>();
    	}
    	
    	List<ZndzFtpPwdRelationExcelVO> configVos = configExcelContent.stream()
    			.filter(e-> !StringUtils.isEmpty(e.getMerchantNo()) && e.getMerchantNo().equalsIgnoreCase(merchantNo))
    			.collect(Collectors.toList());
    	
    	List<StatementExcelNameVO> statements = new ArrayList<StatementExcelNameVO>();
    	for (ZndzFtpPwdRelationExcelVO configVO: configVos) {
    		log.debug("正在从配置 {} 中拉取POS流水", JSON.toJSON(configVO));
    		if (StringUtils.isEmpty(configVO.getFtpUrl())) {
    			continue;
    		}
    		
    		if (StringUtils.isEmpty(configVO.getFtpUser())) {
    			continue;
    		}
    		
    		if (StringUtils.isEmpty(configVO.getFtpPwd())) {
    			continue;
    		}
    		
    		
    		List<StatementExcelNameVO> tempResult = 
    				ftpExcelFetchService.connectAndListFiles(merchantNo, 
    						dealFtpUrl(configVO.getFtpUrl().trim()), 
    						configVO.getFtpUser().trim(),
    						configVO.getFtpPwd().trim());
    		
    		tempResult = tempResult.stream().filter(item -> {
    			
    			List<StatementExcelRecordVO> excelContent = item.getExcelContent();
    			String fileName = item.getFileName();
    			
    			if (StringUtils.isEmpty(fileName)) {
    				log.info("excel 文件名为空！");
    				return false;
    			}
    			
    			if (excelContent == null || excelContent.size() == 0) {
    				log.info("{} 中没有流水，跳过", fileName);
    				return false;
    			}
    			
    			
    			String[] splits = fileName.split("_");
    			if (splits.length < 3) {
    				log.info("{} 名字不合规，不是三段式，跳过", fileName);
    				return false;
    			}
    			
    			
    			String fileDateStr = splits[1];
    			try {
					Date fileDate = new SimpleDateFormat("yyyyMMdd").parse(fileDateStr);
					Date dateDDL = new SimpleDateFormat("yyyyMMdd").parse(podFileDdl);
					if (fileDate.after(dateDDL)) {
						return true;
					}
				} catch (ParseException e1) {
					log.error("解析文件名失败：" + fileName,e1);
					return false;
				}
    			
    			log.info("{} 文件发生在 起始日期 {} 之后，共有{} 条流水，跳过", fileName, podFileDdl, excelContent.size());
				return false;
    			
    		}).collect(Collectors.toList());
    		
    		statements.addAll(tempResult);
    	}
    	
    	Optional<Integer> optional = statements.stream().map(e-> e.getExcelContent().size()).reduce((a,b)->a+b);
    	log.debug("商户号 {} 获取到 {} 个POS流水文件, 总共 {} 条流水", merchantNo, statements.size(), optional.orElse(0));
    	return statements;
    }

    
    
    private String dealFtpUrl(String ftpUrl) {
    	if (StringUtils.isEmpty(ftpUrl)) {
    		return ftpUrl;
    	}
    	
    	
    	ftpUrl = ftpUrl.replaceAll("ftp://", "");
    	
    	return ftpUrl;
    }

}
